package org.dromara.pay.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.dromara.common.core.utils.ProfilesUtils;
import org.dromara.pay.config.WxPayConfig;
import org.dromara.pay.service.QrCodeService;
import org.dromara.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * 获取二维码
 *
 * @author zlj
 * @since 2023/7/31
 */
@Service
@Slf4j
public class QrCodeServiceImpl implements QrCodeService {

    @Autowired
    private WxPayConfig wxPayConfig;
    @Autowired
    @Lazy
    private ISysTenantService tenantService;

    /**
     * 小程序获取二维码
     *
     * @param scene 携带的参数
     * @param page  扫码进入的页面地址 例如： pages/home/index
     * @return 二维码 byte[]  后端 "data:image/jpeg;base64," + new String(Base64.getEncoder().encode(qrCodeBytes))
     * 然后（前端 <img :src="返回结果"/> 就可以）
     */
    @Override
    public byte[] xcxGetQrCode(String scene, String page) {
        try {
            // envVersion: develop #要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
            WxMaService wxMaService = wxPayConfig.wxMaService();
            byte[] qrCodeBytes = wxMaService.getQrcodeService()
                .createWxaCodeUnlimitBytes(
                    scene,
                    page,
                    false,
                    ProfilesUtils.check() ? "release" : "develop",
                    430,
                    true,
                    null,
                    false);
            return qrCodeBytes;
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            //清理ThreadLocal
            WxMaConfigHolder.remove();
        }
    }
}
